
CE.WIDGETS.ANIMATION = {
    
    // set the currently active time period.
    // can be a number (index of period), date (TODO, NYI)
    // or string (css selector);
    set_period: function(n) {
        if (typeof n === "number") {
            if (n < 0) return 0;
            $child = CE.WIDGETS.SLIDER.$.find("td:eq("+n+")");
        } else {
            $child = CE.WIDGETS.SLIDER.$.find( (typeof n === "string") ? "td:"+n : "td:eq("+n+")");
            n = CE.WIDGETS.SLIDER.$.find('td').index($child);
        }
        if ($child.length) {
            this.position = n;
            CE.WIDGETS.SLIDER.click({target:$child.get(0)});
        }
        return $child.length;
    },
    
    position: -1,
    
    playing: 0,
    
    play_step: function () {
        if (!this.set_period(this.position+1)) {
            this.stop();
        }
    },
    
    stop: function () {
        if (!this.playing) return;
        $("#ce_play_button").css('background-position', '-12px 2px');
        this.playing = false;
        clearInterval(this.play_interval);
        //console.info('stopping playback.');
    },
    
    play: function () {
        if (this.playing) return;
        $("#ce_play_button").css('background-position', '-36px 2px');
        this.playing = true;
        //console.info('starting playback.');
        this.play_interval = setInterval("CE.WIDGETS.ANIMATION.play_step()", 1000);
    },
    
    init: function () {
        // click handler for the play control.
        $('#ce_play_controls').click(function (evt) {
            
            // PLAY BUTTON
            if (evt.target.id === "ce_play_button") {
                if (this.playing) {
                    this.stop();
                } else {
                    this.play();
                }
            }
            
            // STEP BACKWARDS
            else if (evt.target.id === "ce_rew_button") {
                this.stop();
                this.set_period(this.position - 1);
            }
            
            // STEP FORWARD
            else if (evt.target.id === "ce_ff_button") {
                this.stop();
                this.set_period(this.position + 1);
            }
            
            // GO TO START
            else if (evt.target.id === "ce_start_button") {
                this.stop();
                this.set_period(0);
            }
            
            // GO TO END
            else if (evt.target.id === "ce_end_button") {
                this.stop();
                this.set_period("last");
            }
            
        }.createDelegate(this));
    }
};